package com.exampletest.controller;

import com.exampletest.model.Meeting;
import com.exampletest.service.MeetingService;
import com.exampletest.util.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/admin/meeting")

public class AdminMeetingController {
    @Autowired
    private MeetingService meetingService;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    @Value("${app.upload.path}")
    private String uploadPath;

    @Value("${app.upload.url-prefix}")
    private String urlPrefix;

    @GetMapping("/list")
    public String list(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "startDate", required = false) String startDateStr,
            @RequestParam(value = "endDate", required = false) String endDateStr,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "5") int size,
            Model model,
            RedirectAttributes redirectAttributes
    ) {
        try {
            // 创建分页请求
            Pageable pageable = PageRequest.of(page, size);

            // 调用分页服务
            Page<Meeting> meetingsPage = meetingService.searchMeetingsWithPage(
                    keyword, startDateStr, endDateStr, pageable
            );

            // 添加结果到模型
            model.addAttribute("meetings", meetingsPage.getContent());
            model.addAttribute("page", meetingsPage);

            // 保留搜索参数
            model.addAttribute("keyword", keyword);
            model.addAttribute("startDate", startDateStr);
            model.addAttribute("endDate", endDateStr);
            model.addAttribute("status", status);

            return "meeting/audit_list";
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("error", "获取会议列表失败: " + e.getMessage());
            return "redirect:/admin/meeting/list";
        }
    }

    @GetMapping("/add")
    public String addPage() {
        return "meeting/audit_add";
    }

    @PostMapping("/add")
    public String add(Meeting meeting, @RequestParam(value = "file", required = false) MultipartFile file, Model model) {
        meeting.setCreateTime(new Date());
        meeting.setIsApproved(0); // 默认待审核
        meeting.setIsDeleted(0);
        try {
            if (file != null && !file.isEmpty()) { // 先检查 file 是否为 null
                String fileName = FileUploadUtil.generateUniqueFileName(file.getOriginalFilename());
                FileUploadUtil.saveFile(uploadPath, fileName, file);

                meeting.setCoverImage(urlPrefix + fileName);
            }

            meetingService.addMeeting(meeting);
            return "redirect:/admin/meeting/list";
        } catch (IOException e) {
            model.addAttribute("error", "添加会议失败：" + e.getMessage());
            return "meeting/audit_add";
        }
    }

    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, Model model) {
        model.addAttribute("meeting", meetingService.getMeetingById(id));
        return "meeting/audit_edit";
    }

    @PostMapping("/edit")
    public String edit(
            Meeting meeting,
            @RequestParam(value = "file", required = false) MultipartFile file,
            Model model
    ) {
        try {
            // 处理图片上传
            if (file != null && !file.isEmpty()) {
                String fileName = FileUploadUtil.generateUniqueFileName(file.getOriginalFilename());
                FileUploadUtil.saveFile(uploadPath, fileName, file);
                meeting.setCoverImage(urlPrefix + fileName);
            }

            meetingService.updateMeeting(meeting);
            return "redirect:/admin/meeting/list";
        } catch (IOException e) {
            model.addAttribute("error", "更新会议失败：" + e.getMessage());
            return "meeting/audit_edit";
        }
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        meetingService.deleteMeeting(id);
        return "redirect:/admin/meeting/list";
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Meeting meeting = meetingService.getMeetingById(id);
        model.addAttribute("meeting", meeting);
        return "meeting/audit_detail";
    }

    @GetMapping("/approve/{id}")
    public String approve(@PathVariable Integer id, @RequestParam("status") Integer status, RedirectAttributes redirectAttributes) {
        try {
            meetingService.approveMeeting(id, status);
            redirectAttributes.addFlashAttribute("success", "会议审核成功");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("error", "会议审核失败: " + e.getMessage());
        }
        return "redirect:/admin/meeting/list";
    }
}
